import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import pyautogui
import time
def screen_video():
    # 水印文字
    watermark_text = "这是一个水印"
    # 录制的视频文件名
    output_filename = "output_video.mp4"
    # 屏幕分辨率
    screen_width, screen_height = pyautogui.size()

    # 设置视频编码和帧率
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 使用mp4编码
    fps = 30
    out = cv2.VideoWriter(output_filename, fourcc, fps, (screen_width, screen_height))

    # 设置字体
    font_path = "C:\\Windows\\Fonts\\msyh.ttc"  # 微软雅黑字体路径（Windows）
    font_size = 24
    font = ImageFont.truetype(font_path, font_size)

    # 录制时长（秒）
    record_duration = 10
    start_time = time.time()

    # 水印间距
    watermark_spacing = 200  # 水印之间的间距，可以根据需要调整

    def add_tiled_watermark(image, text, font, angle=45):
        """在图像上添加倾斜45度并平铺的水印"""
        # 将图像转换为Pillow格式
        pil_image = Image.fromarray(image)
        draw = ImageDraw.Draw(pil_image)

        # 创建单个水印的图像并旋转
        text_width, text_height = draw.textbbox((0, 0), text, font=font)[2:]
        watermark_image = Image.new('RGBA', (text_width, text_height), (0, 0, 0, 0))
        watermark_draw = ImageDraw.Draw(watermark_image)
        watermark_draw.text((0, 0), text, font=font, fill=(255, 255, 255, 100))
        rotated_watermark = watermark_image.rotate(angle, expand=True)

        # 获取旋转后水印的尺寸
        rotated_width, rotated_height = rotated_watermark.size

        # 在整个屏幕上平铺水印
        for y in range(-rotated_height, screen_height, watermark_spacing):
            for x in range(-rotated_width, screen_width, watermark_spacing):
                pil_image.paste(rotated_watermark, (x, y), rotated_watermark)

        return np.array(pil_image)

    # 录屏并添加水印
    while True:
        # 截取屏幕并转换为BGR格式
        screenshot = pyautogui.screenshot()
        frame = np.array(screenshot)
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

        # 添加平铺的倾斜水印
        frame_with_watermark = add_tiled_watermark(frame, watermark_text, font, angle=45)

        # 写入视频文件
        out.write(frame_with_watermark)

        # 计算已录制的时长，确保录制时长为10秒
        if time.time() - start_time >= record_duration:
            break

        # 确保每秒30帧
        time.sleep(1 / fps)

    # 释放资源
    out.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    screen_video()
